<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
    <title>
        自制客流量数据
    </title>

    <style>
        html,
        body,
        #viewDiv {
            padding: 0;
            margin: 0;
            height: 100%;
            width: 100%;
        }

        #timeSlider {
            position: absolute;
            left: 100px;
            right: 100px;
            bottom: 30px;
        }

        #infoDiv {
            height: 200px;
            padding: 10px;
            width: 280px;
        }

        #infoDiv span {
            color: #f9c653;
            font-size: 12pt;
            font-weight: bolder;
        }
    </style>

    <link rel="stylesheet" href="https://js.arcgis.com/4.17/esri/themes/light/main.css" />
    <script src="https://js.arcgis.com/4.17/"></script>
    <script>
        require([
            "esri/Map",
            "esri/views/MapView",
            "esri/layers/GeoJSONLayer",
            "esri/widgets/TimeSlider",
            "esri/widgets/Expand",
            "esri/widgets/Legend",
            "esri/widgets/AreaMeasurement2D",
            "esri/widgets/Compass",
            "esri/widgets/Fullscreen",
            "esri/widgets/Home",
            "esri/widgets/ScaleBar",
            "esri/widgets/NavigationToggle"
        ], function (Map, MapView, GeoJSONLayer, TimeSlider, Expand, Legend, AreaMeasurement2D, Compass, Fullscreen, Home, ScaleBar, NavigationToggle) {
            let layerView;

            const layer = new GeoJSONLayer({
                url:
                    "https://bsvensson.github.io/various-tests/geojson/usgs-earthquakes-06182019.geojson",
                    //"http://localhost:8080/usgs-earthquakes-06182019.geojson",
                copyright: "王觉非",
                title: "自制客流量数据",
                // set the CSVLayer's timeInfo based on the date field
                timeInfo: {
                    startField: "time", // name of the date field
                    interval: {
                        // set time interval to one day
                        unit: "days",
                        value: 1
                    }
                },
                renderer: {
                    type: "simple",
                    field: "mag",
                    symbol: {
                        type: "simple-marker",
                        color: "orange",
                        outline: null
                    },
                    visualVariables: [
                        {
                            type: "size",
                            field: "mag",
                            stops: [
                                {
                                    value: 1,
                                    size: "5px"
                                },
                                {
                                    value: 2,
                                    size: "15"
                                },
                                {
                                    value: 3,
                                    size: "35"
                                }
                            ]
                        },
                        {
                            type: "color",
                            field: "depth",
                            stops: [
                                {
                                    value: 2.5,
                                    color: "#F9C653",
                                    label: "<2km"
                                },
                                {
                                    value: 3.5,
                                    color: "#F8864D",
                                    label: "3km"
                                },
                                {
                                    value: 4,
                                    color: "#C53C06",
                                    label: ">4km"
                                }
                            ]
                        }
                    ]
                },
                popupTemplate: {
                    title: "{title}",
                    content: [
                        {
                            type: "fields",
                            fieldInfos: [
                                {
                                    fieldName: "place",
                                    label: "地名",
                                    visible: true
                                },
                                {
                                    fieldName: "mag",
                                    //label: "Magnitude",
                                    label: "峰值（千人）",
                                    visible: true
                                },
                                {
                                    fieldName: "depth",
                                    //label: "Depth",
                                    label: "有效半径",
                                    visible: true
                                }
                            ]
                        }
                    ]
                }
            });

            const map = new Map({
                basemap: "gray-vector",
                layers: [layer]
            });

            var view = new MapView({
                map: map,
                container: "viewDiv",
                zoom: 13,
                center: [-117.50268, 34.04713]
            });

            var compass=new Compass({
                view: view
            });
            view.ui.add(compass, "top-left");
            var navigation=new NavigationToggle({
                view:view
            });
            view.ui.add(navigation,"top-left");

            // create a new time slider widget
            // set other properties when the layer view is loaded
            // by default timeSlider.mode is "time-window" - shows
            // data falls within time range
            const timeSlider = new TimeSlider({
                container: "timeSlider",
                playRate: 50,
                stops: {
                    interval: {
                        value: 1,
                        unit: "hours"
                    }
                }
            });
            view.ui.add(timeSlider, "manual");

            // wait till the layer view is loaded
            view.whenLayerView(layer).then(function (lv) {
                layerView = lv;

                // start time of the time slider - 5/25/2019
                const start = new Date(2019, 4, 25);
                // set time slider's full extent to
                // 5/25/5019 - until end date of layer's fullTimeExtent
                timeSlider.fullTimeExtent = {
                    start: start,
                    end: layer.timeInfo.fullTimeExtent.end
                };

                // We will be showing earthquakes with one day interval
                // when the app is loaded we will show earthquakes that
                // happened between 5/25 - 5/26.
                const end = new Date(start);
                // end of current time extent for time slider
                // showing earthquakes with one day interval
                end.setDate(end.getDate() + 1);

                // Values property is set so that timeslider
                // widget show the first day. We are setting
                // the thumbs positions.
                timeSlider.values = [start, end];
            });

            // watch for time slider timeExtent change
            timeSlider.watch("timeExtent", function () {
                // only show earthquakes happened up until the end of
                // timeSlider's current time extent.
                layer.definitionExpression =
                    "time <= " + timeSlider.timeExtent.end.getTime();

                // now gray out earthquakes that happened before the time slider's current
                // timeExtent... leaving footprint of earthquakes that already happened
                layerView.effect = {
                    filter: {
                        timeExtent: timeSlider.timeExtent,
                        geometry: view.extent
                    },
                    excludedEffect: "grayscale(20%) opacity(12%)"
                };

                // run statistics on earthquakes fall within the current time extent
                const statQuery = layerView.effect.filter.createQuery();
                statQuery.outStatistics = [
                    magMax,
                    magAvg,
                    magMin,
                    tremorCount,
                    avgDepth
                ];

                layer
                    .queryFeatures(statQuery)
                    .then(function (result) {
                        let htmls = [];
                        statsDiv.innerHTML = "";
                        if (result.error) {
                            return result.error;
                        } else {
                            if (result.features.length >= 1) {
                                var attributes = result.features[0].attributes;
                                for (name in statsFields) {
                                    if (attributes[name] && attributes[name] != null) {
                                        const html =
                                            "<br/>" +
                                            statsFields[name] +
                                            ": <b><span> " +
                                            attributes[name].toFixed(2) +
                                            "</span></b>";
                                        htmls.push(html);
                                    }
                                }
                                var yearHtml =
                                    "<span>" +
                                    result.features[0].attributes["tremor_count"] +
                                    "</span> 个客流量峰值在 " +
                                    timeSlider.timeExtent.start.toLocaleDateString() +
                                    " - " +
                                    timeSlider.timeExtent.end.toLocaleDateString() +
                                    " 中间被记录" +
                                    "。<br/>";

                                if (htmls[0] == undefined) {
                                    statsDiv.innerHTML = yearHtml;
                                } else {
                                    statsDiv.innerHTML =
                                        yearHtml + htmls[0] + htmls[1] + htmls[2] + htmls[3];
                                }
                            }
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            });

            const avgDepth = {
                onStatisticField: "depth",
                outStatisticFieldName: "Average_depth",
                statisticType: "avg"
            };

            const magMax = {
                onStatisticField: "mag",
                outStatisticFieldName: "Max_magnitude",
                statisticType: "max"
            };

            const magAvg = {
                onStatisticField: "mag",
                outStatisticFieldName: "Average_magnitude",
                statisticType: "avg"
            };

            const magMin = {
                onStatisticField: "mag",
                outStatisticFieldName: "Min_magnitude",
                statisticType: "min"
            };

            const tremorCount = {
                onStatisticField: "mag",
                outStatisticFieldName: "tremor_count",
                statisticType: "count"
            };

            const statsFields = {
                /*Max_magnitude: "Max magnitude",
                Average_magnitude: "Average magnitude",
                Min_magnitude: "Min magnitude",
                Average_depth: "Average Depth"*/
                Max_magnitude: "峰值最大值",
                Average_magnitude: "平均峰值",
                Min_magnitude: "峰值最小值",
                Average_depth: "平均有效半径"
            };

            // add a legend for the earthquakes layer
            const legendExpand = new Expand({
                collapsedIconClass: "esri-icon-collapse",
                expandIconClass: "esri-icon-expand",
                expandTooltip: "Legend",
                view: view,
                content: new Legend({
                    view: view
                }),
                expanded: false
            });
            view.ui.add(legendExpand, "top-left");

            const statsDiv = document.getElementById("statsDiv");
            const infoDiv = document.getElementById("infoDiv");
            const infoDivExpand = new Expand({
                collapsedIconClass: "esri-icon-collapse",
                expandIconClass: "esri-icon-expand",
                expandTooltip: "Expand spot info",
                view: view,
                content: infoDiv,
                expanded: true
            });
            view.ui.add(infoDivExpand, "top-right");

            var measurementWidget=new AreaMeasurement2D({
                view: view
            });
            view.ui.add(measurementWidget, "top-left");
            var fullscreen=new Fullscreen({
                view: view
            });
            view.ui.add(fullscreen,"top-right");
            var homeBtn=new Home({
                view: view
            });
            view.ui.add(homeBtn,"top-right");

            var scaleBar=new ScaleBar({
                view: view
            });
            view.ui.add(scaleBar, "bottom-left");
        });
    </script>
</head>

<body>
    <div id="viewDiv"></div>
    <div id="timeSlider"></div>
    <div id="infoDiv" class="esri-widget">
        <div><b>选定时间段简单统计</b></div>
        <br />
        <div id="statsDiv" class="esri-widget"></div>
    </div>
</body>

</html>